import 'dart:async';

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/app_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/user_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/model/user_open_entity.dart';
import 'package:flutter_taotaoshipin/pages/login/local_user_info.dart';
import 'package:flutter_taotaoshipin/pages/login/login_routes.dart';
import 'package:flutter_taotaoshipin/pages/splash/privacy_dialog.dart';
import 'package:flutter_taotaoshipin/routes/app_routes.dart';
import 'package:flutter_taotaoshipin/util/device_utils.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:oaid_kit/oaid_kit.dart';
import 'package:rxdart/rxdart.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:uuid/uuid.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  StreamSubscription<dynamic>? _subscription;
  // 广告状态监听
  StreamSubscription? _adSubscription;
  bool loadingSplash = true;
  // 初始化数据
  UserOpenEntity? userOpenEntity;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      /// 隐私弹窗
      _initPrivacy();
    });
  }

  @override
  void dispose() {
    _subscription?.cancel();
    _adSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      // color: Color(0xFF406EF0),
      child: LoadAssetImage(
        'launchimage',
        fit: BoxFit.cover,
      ),
    );
  }

  /// 隐私弹窗
  void _initPrivacy() {
    _subscription = Stream.value(1)
        .delay(const Duration(milliseconds: 300))
        .listen((_) async {
      if (!SpUtil.getBool(SpKey.privacy, defValue: false)!) {
        /// 隐私弹窗
        await Get.dialog(
          PrivacyDialog(),
          barrierDismissible: false,
        );
      }

      if (Device.isIOS) {
        // 获取idfa
        await initAppTrackingTransparencyPlugin();
      }
      if (Device.isAndroid) {
        // 获取oaid
        await initOaidKit();
      }

      AppController appController = Get.find();
      // 友盟
      UmengCommonSdk.initCommon(Constant.umandAppKey, Constant.umiosAppKey,
          appController.appProfile.agentName!);
      UmengCommonSdk.setPageCollectionModeManual();

      // 是否切换
      await _loadMainOpenData();
    });
  }

  Future<void> _loadMainOpenData() async {
    try {
      var result = await AppDao.iosInspect();
      if (result.code == 0) {
        // 请求结果成功，数据不为空
        if (result.data != null) {
          // 初始化
          _loadUserOpenData();
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
      return;
    } on HiNetError {
      // EasyLoading.showToast(e.message);
    } catch (e) {
      // EasyLoading.showToast(e.toString());
    }

    /// 重试
    Future.delayed(const Duration(milliseconds: 1500), () {
      _loadMainOpenData();
    });
  }

  /// 初始化接口
  Future<void> _loadUserOpenData() async {
    // 错误信息
    var errorMsg = '';
    // 自动生成账号
    try {
      var result = await UserDao.open();
      if (result.code == 0) {
        // 请求结果成功，数据不为空
        if (result.data != null) {
          // 返回打开记录状态 0 成功 1失败
          if (result.data!.status == 0) {
            // 成功
            userOpenEntity = result.data;
            // 穿山甲
            initCsj(result.data!.csj);
            return;
          } else {
            errorMsg = '初始化失败';
          }
        } else {
          errorMsg = '数据为空';
        }
      } else {
        errorMsg = result.message;
      }
    } on HiNetError catch (e) {
      errorMsg = e.message;
    } catch (e) {
      errorMsg = e.toString();
    }
    // 显示错误信息
    EasyLoading.showToast(errorMsg);
  }

  Future<void> _loadUserLoginData(String user, String pwd) async {
    // 错误信息
    var errorMsg = '';
    try {
      var result = await UserDao.login(user, pwd);
      if (result.code == 0) {
        // 登录成功
        if (result.data != null) {
          // 请求结果成功，数据不为空
          if (result.data!.id != null && result.data!.sessionId != null) {
            // 保存本地
            var userInfo = LocalUserInfo2(
              user: user,
              password: pwd,
              mId: result.data!.id.toString(),
              sessionId: result.data!.sessionId,
            );
            var appController = Get.find<AppController>();
            appController.updateLocaleUserinfo(userInfo);

            // 更新归因
            var chnId = result.data?.dye?.chnId;
            if (chnId != null && chnId != 0) {
              appController.appProfile.chnId = chnId;
            }
            var ver = result.data?.dye?.ver;
            if (ver != null && ver != '') {
              appController.appProfile.ver = ver;
            }
            var agentName = result.data?.dye?.agentName;
            if (agentName != null && agentName != '') {
              appController.appProfile.agentName = agentName;
            }
            appController.updateAppProfile(appController.appProfile);

            // 自动播放参数
            appController.userLoginPlay = result.data!.play;
            // 进入主页
            Get.offAllNamed(AppRoutes.rootTab);

            return;
          } else {
            errorMsg = '登录失败';
          }
        } else {
          errorMsg = '数据为空';
        }
      } else {
        errorMsg = result.message;
      }
    } on HiNetError catch (e) {
      errorMsg = e.message;
    } catch (e) {
      errorMsg = e.toString();
    }
    // 显示错误信息
    EasyLoading.showToast(errorMsg);
    // 手动登录
    Get.offNamed(LoginRoutes.phoneLogin, arguments: {'type': 1});
  }

  /// ios申请追踪权限，获取idfa
  Future<void> initAppTrackingTransparencyPlugin() async {
    final TrackingStatus status =
        await AppTrackingTransparency.trackingAuthorizationStatus;
    // If the system can show an authorization request dialog
    if (status == TrackingStatus.notDetermined) {
      // Request system's tracking authorization dialog
      await AppTrackingTransparency.requestTrackingAuthorization();
    }

    var idfa = await AppTrackingTransparency.getAdvertisingIdentifier();
    // 保存
    if (idfa == '00000000-0000-0000-0000-000000000000') {
      String? oldIdfa;
      try {
        oldIdfa = await const FlutterSecureStorage().read(key: SpKey.idfa);
      } catch (e) {
        debugPrint('钥匙串读取失败$e');
      }
      if (oldIdfa == null) {
        // 重新生成
        idfa = 'sj-${const Uuid().v1()}';
      } else {
        idfa = oldIdfa;
      }
    }
    await SpUtil.putString(SpKey.idfa, idfa);
    await const FlutterSecureStorage().write(key: SpKey.idfa, value: idfa);
  }

  /// 安卓获取oaid
  Future<void> initOaidKit() async {
    final oaid = await Oaid.instance.getOaid();
    if (oaid.oaid != null &&
        oaid.oaid != '00000000-0000-0000-0000-000000000000') {
      // 保存本地
      await SpUtil.putString(SpKey.oaid, oaid.oaid!);
    } else {
      var res = const Uuid().v1();
      await SpUtil.putString(SpKey.oaid, res);
    }
  }

  Future<void> startAutoLogin() async {
    // 是否游客自动注册登陆 0 自动 1 手动
    if (userOpenEntity!.auto == 0) {
      // 自动登录
      if (userOpenEntity!.userName!.isNotEmpty &&
          userOpenEntity!.userPwd!.isNotEmpty) {
        await _loadUserLoginData(
            userOpenEntity!.userName!, userOpenEntity!.userPwd!);
        return;
      } else {
        // 读取本地账号密码
        var appController = Get.find<AppController>();
        if (appController.localUserInfo.user != null &&
            appController.localUserInfo.password != null) {
          // 本地有账号密码
          await _loadUserLoginData(appController.localUserInfo.user!,
              appController.localUserInfo.password!);
          return;
        } else if (appController.localUserInfo.mId != null &&
            appController.localUserInfo.sessionId != null) {
          // 本地有sessionid
          // 进入主页
          Get.offAllNamed(AppRoutes.rootTab);

          return;
        } else {
          // 跳转手机登录
          Get.offAllNamed(LoginRoutes.phoneLogin, arguments: {'type': 1});
        }
      }
    } else {
      // 跳转手机登录
      Get.offAllNamed(LoginRoutes.phoneLogin, arguments: {'type': 1});
    }
  }

  /// 初始化穿山甲
  Future<void> initCsj(UserOpenCsj? csj) async {
    if (csj != null) {
      var appController = Get.find<AppController>();
      appController.updateCsj(csj);
      // bool? res1 = await TtspGromore.instance.initSDK(appId: csj.appId!);
      // print('Gromore初始化结果$res1');
      // // 初始化穿山甲短剧
      // bool? res2 = await TtspPangrowth().initSDK();
      // print('Pangrowth初始化结果$res2');
      // // 开屏
      // if (csj.list != null) {
      //   var open =
      //       csj.list!.firstWhereOrNull((element) => element.adverType == '1');
      //   if (open != null) {
      //     TtspGromore.instance.loadSplashAd(adId: open.adverId!);
      //     return;
      //   }
      // }
      // 自动登录
      startAutoLogin();
    } else {
      // 自动登录
      startAutoLogin();
    }
  }
}
